#include "preHeader.h"
#include "CrossServer.h"
#include "Service/CrossServerService.h"
#include "Session/PacketDispatcher.h"
#include "PlayBossMgr.h"

CrossServer::CrossServer()
: m_pService(new CrossServerService())
, sWheelTimerMgr(1, GET_UNIX_TIME)
{
}

CrossServer::~CrossServer()
{
}

bool CrossServer::Initialize()
{
	sPlayBossMgr.Init();
	return FrameWorker::Initialize();
}

void CrossServer::Update(uint64 diffTime)
{
	AsyncTaskOwner::UpdateTask();
	m_pService->UpdateAllPackets();
}

void CrossServer::OnTick()
{
	sWheelTimerMgr.Update(GET_UNIX_TIME);
}

void CrossServer::SendError2Client(const ClientAddr4Cross& clientAddr, GErrorCode error)
{
	NetPacket pack(SMSG_ERROR);
	pack << error;
	TransPacket2Client(clientAddr, pack);
}

void CrossServer::TransPacket2Instance(InstGUID instGuid, const INetPacket& pck)
{
	NetPacket trans(SMC_TRANS_INSTANCE_PACKET);
	trans << instGuid;
	trans.WritePacket(pck);
	sPacketDispatcher.SendPacket2Mapserver(trans);
}

void CrossServer::TransPacket2Player(ObjGUID playerGuid, const INetPacket& pck)
{
	NetPacket trans(SMC_TRANS_PLAYER_PACKET);
	trans << playerGuid;
	trans.WritePacket(pck);
	sPacketDispatcher.SendPacket2Mapserver(trans);
}

void CrossServer::TransPacket2Client(const ClientAddr4Cross& clientAddr, const INetPacket& pck)
{
	NetPacket trans(SMC_TRANS_CLIENT_PACKET);
	trans << clientAddr;
	trans.WritePacket(pck);
	sPacketDispatcher.SendPacket2Mapserver(trans);
}

void CrossServer::TransPacket2GameServer(uint32 gsIdx, const INetPacket& pck)
{
	NetPacket trans(SMC_TRANS_GAME_SERVER_PACKET);
	trans << gsIdx;
	trans.WritePacket(pck);
	sPacketDispatcher.SendPacket2Mapserver(trans);
}

void CrossServer::StartInstance(InstGUID fakeInstGuid, ObjGUID instOwner,
	uint32 opCodeResp, uint32 flags, const std::string_view& args)
{
	NetPacket pack(SMC_START_INSTANCE);
	pack << fakeInstGuid << instOwner << opCodeResp << flags;
	pack.Append(args.data(), args.size());
	sPacketDispatcher.SendPacket2Mapserver(pack);
}

void CrossServer::StopInstance(InstGUID instGuid)
{
	NetPacket pack(SMC_STOP_INSTANCE);
	pack << instGuid;
	sPacketDispatcher.SendPacket2Mapserver(pack);
}

void CrossServer::TeleportPlayer(ObjGUID playerGuid, InstGUID instGuid,
	const vector3f1f& tgtPos, TeleportType tpType, uint32 tpFlags,
	const std::string_view& tpArgs)
{
	NetPacket tpPacket(MS_SWITCH_MAP);
	tpPacket << GetGuid4Gs(playerGuid)
		<< instGuid << tgtPos << (s32)tpType << tpFlags << tpArgs;
	TransPacket2GameServer(playerGuid.SID, tpPacket);
}
